use time::macros::format_description;
use time::UtcOffset;
use tracing_error::ErrorLayer;
use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, Registry, util::SubscriberInitExt};
use tracing_subscriber::fmt::format::{DefaultFields, Format, Full};
use tracing_subscriber::fmt::Layer;
use tracing_subscriber::fmt::time::OffsetTime;
use crate::logger::{LogConfig, non_blocking};
use crate::logger::logger::RollingFileAppender;
use crate::logger::non_blocking::NonBlocking;

pub fn set_logger<'a>(offset_time: UtcOffset, log_config: &LogConfig) -> &'a RollingFileAppender {
    let env_filter = EnvFilter::new(
        std::env::var("RUST_LOG").unwrap_or_else(|_| log_config.level().to_owned()),
    );

    let local_time = OffsetTime::new(
        offset_time,
        format_description!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]"),
    );

    // 输出到控制台中
    let console_layer = fmt::layer()
        .pretty()
        .with_timer(local_time.clone())
        .with_writer(std::io::stderr);

    // 输出到文件中
    // let file_appender = rolling::daily(CONFIG.read().await.log_config().path(), CONFIG.read().await.log_config().file_name());
    let file_appender: &'a RollingFileAppender = &super::logger::minutely(offset_time, log_config.path(), log_config.file_name());
    let (non_blocking_appender, _guard) = non_blocking(file_appender.clone());
    let file_layer = fmt::layer()
        .with_ansi(false)
        .with_timer(local_time)
        .with_writer(non_blocking_appender);

    Registry::default()
        .with(env_filter)
        .with(ErrorLayer::default())
        .with(console_layer)
        .with(file_layer)
        .init();

    // 安裝 color-eyre 的 panic 处理句柄
    color_eyre::install().unwrap();
    file_appender
}